import 'package:flutter/foundation.dart';
import 'package:flutter_baselib/flutter_baselib.dart';
import 'package:flutter_baselib_example/common/net/bean_factory.dart';
import 'package:flutter_baselib_example/common/net/http_urls.dart';
import 'package:flutter_baselib_example/common/net/util/juhe_json_utils.dart';

///@date:  2021/2/26 21:19
///@author:  lixu
///@description: http json解析工具
class HttpJsonUtils {
  static String _tag = 'HttpJsonUtils';

  ///TODO 参考下面代码逻辑，根据业务修改代码解析json为object
  ///TODO 最终就是要将json转换为Object或List并封装到HttpResultBean对象中

  ///http响应json解析成对象
  ///[jsonData] http响应完整json
  ///[isRespListData] 响应数据是否是List格式
  ///[isUseCompute] 是否使用compute方法解析json
  static Future<HttpResultBean<T>> parseJsonToObject<T>(String url, Map<String, dynamic> jsonData, bool isRespListData, {bool isUseCompute = false}) async {
    if (isUseCompute) {
      ///使用compute 解析json，耗时会明显增加，根据自身业务决定是否使用compute
      ///参考：https://flutter.dev/docs/cookbook/networking/background-parsing 进行优化
      Map<String, dynamic> params = {'url': url, 'jsonData': jsonData, 'isRespListData': isRespListData};
      return compute(_computeParseJson, params);
    } else {
      return _commonParseJson<T>(url, jsonData, isRespListData);
    }
  }

  ///使用compute 解析json
  static Future<HttpResultBean<T>> _computeParseJson<T>(Map<String, dynamic> params) {
    return _commonParseJson(params['url'], params['jsonData'], params['isRespListData']);
  }

  ///通用的json解析
  static Future<HttpResultBean<T>> _commonParseJson<T>(String url, Map<String, dynamic> jsonData, bool isRespListData) async {
    ///TODO 聚合接口和https://wv.widevision.com.cn/接口返回的数据格式不一样，需要区分解析json
    if (url.contains(HttpUrls.juheHost)) {
      ///TODO 聚合接口响应数据解析
      return JuheJsonUtils.juheApiParseJson(url, jsonData, isRespListData);
    }

    HttpResultBean<T> resultBean = HttpResultBean();
    resultBean.isRespListData = isRespListData;

    try {
      resultBean.code = jsonData['code']?.toString() ?? HttpCode.defaultCode;
      resultBean.message = jsonData['message'];

      if (isRespListData) {
        ///响应的是list
        resultBean.dataList = await _parseToListObject(url, jsonData, resultBean.code);
      } else {
        ///响应的是object
        resultBean.data = await _parseToObject(url, jsonData, resultBean.code);
      }
    } catch (exception) {
      LogUtils.e(_tag, exception.toString());

      if (resultBean.code == HttpCode.defaultCode || HttpCode.successCodeList.contains(resultBean.code)) {
        if (HttpCode.successCodeList.contains(resultBean.code)) {
          resultBean.message = exception.toString();
        }
        resultBean.code = HttpCode.jsonParseException;
      }
    }

    return resultBean;
  }

  ///json解析为list
  ///[jsonData] json数据
  ///[code] http响应码
  static Future<List<T>> _parseToListObject<T>(String url, Map<String, dynamic>? jsonData, String code) async {
    var body = jsonData?['data'];

    List<T> listData = [];

    if (HttpCode.successCodeList.contains(code) && body == null) {
      ///请求成功,响应无data,不用解析
    } else {
      if (HttpCode.successCodeList.contains(code) && body != null && body is List) {
        body.forEach((value) async {
          T? bean = BeanFactory.parseObject<T>(value);
          if (bean != null) {
            listData.add(bean);
          }
        });
      }
    }
    return listData;
  }

  ///json解析为object
  ///[jsonData] json数据
  ///[code] http响应码
  static Future<T?> _parseToObject<T>(String url, Map<String, dynamic>? jsonData, String code) async {
    if (HttpCode.successCodeList.contains(code) && jsonData == null) {
      ///请求成功,响应无data,不用解析
      return null;
    } else {
      return BeanFactory.parseObject<T>(jsonData);
    }
  }
}
